package com.ruoyi;

import com.ruoyi.file.annotation.FTPClientAnnotation;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

@RunWith(SpringRunner.class)
@SpringBootTest
public class Ftptest {

    @Value("${ftp.host}")
    public String host;
    @Value("${ftp.port}")
    public Integer port;
    @Value("${ftp.username}")
    public String username;
    @Value("${ftp.password}")
    public String password;
    @Value("${ftp.rootdirectory}")
    public String rootdirectory;

    public FTPClient getFTPClient() throws IOException {
        FTPClient ftpClient = new FTPClient();
        ftpClient.connect(host, port);
        ftpClient.login(username, password);
        boolean login = ftpClient.login(username, password);
        if (!login) {
            throw new IOException("connected fail....");
        }
        return ftpClient;
    }

    @Test
    public void upftp() throws IOException {
        int reply;
        FTPClient ftp = new FTPClient();
        ftp.connect(host, port);
        ftp.login(username, password);
        ftp.setFileType(2);

        reply=ftp.getReplyCode();
        if(!FTPReply.isPositiveCompletion(reply)){
            //说明连接失败，需要断开连接
            ftp.disconnect();
            System.out.println("连接失败");
        }
        File file = new File("C:/Users/羡慕南飞的燕/Desktop/ceshi/ccc.xlsx");//指定路径
         InputStream fis = new FileInputStream(file);
        String filePath = "ftps/ff/yy";
        //boolean b = ftp.changeWorkingDirectory(filePath);
        if(!ftp.changeWorkingDirectory(filePath)){
            //创建目录
            String[] dirs = filePath.split("/");
            String tempPath = "";
            for (String dir: dirs) {
                tempPath += "/"+dir;
                if(!ftp.changeWorkingDirectory(tempPath)){
                    if(!ftp.makeDirectory(tempPath)){
                        System.out.println("无法创建文件夹 ");
                    }else{
                        ftp.changeWorkingDirectory(tempPath);
                    }
                }
            }
        }
        boolean storeFile = ftp.storeFile("ccc.xlsx", fis);
        if (storeFile) {
            System.out.println("upload success....");
        } else {
            System.out.println("upload fail.....");
        }
        fis.close();
        ftp.logout();
        System.out.println("完成。。。。 ");
    }


    @FTPClientAnnotation
    public void hhh(){
        System.out.println("99999999");
    }




}
